package com.team9.fitness.service.impl;

import com.team9.fitness.entity.Diet;
import com.team9.fitness.entity.Meal;
import com.team9.fitness.mapper.DietMapper;
import com.team9.fitness.service.DietService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DietServiceImpl implements DietService {

    @Autowired
    private DietMapper dietMapper;

    @Override
    public ResponseEntity<Map<String, Object>> getAll() {

        List<Meal> meals = new ArrayList<>();
        dietMapper.getBelongs().stream().forEach(
                belong -> {
                    Meal meal = new Meal();
                    meal.setDiets(dietMapper.getByBelong(belong));
                    meal.setId(belong);
                    meals.add(meal);
                });

        Map<String, Object> response = new HashMap<>();
        response.put("meals", meals);

        return ResponseEntity.ok(response);
    }

    @Override
    public ResponseEntity<Map<String, Object>> save(Long id, List<Diet> diets) {
        try {
            dietMapper.save(id, diets);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "饮食计划保存成功");
            response.put("id", id);
            response.put("dietsCount", diets != null ? diets.size() : 0);

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "饮食计划保存失败: " + e.getMessage());
            response.put("error", e.getMessage());

            return ResponseEntity.ok(response);
        }
    }
}
